<form class="well form-horizontal margin-horisontal" action="" method="POST" name="form_new_ds" id="form_new_ds">
    <fieldset>
        <legend><?php echo Arr::getValue($params, 'legend', ''); ?></legend>

        <?php echo Arr::getValue($params, 'message', ''); ?>
        <?php echo Arr::getValue($params, 'error', ''); ?>

        <input type="hidden" name="action" value="<?php echo Arr::getValue($params, 'action', 0); ?>">
        <input type="hidden" name="id" value="<?php echo Arr::getValue($params, 'id', 0); ?>">

        <div class="control-group">
            <label class="control-label" for="tbl">Имя таблицы в БД Репортс</label>
            <div class="controls">
                <input type="text" class="input-xlarge" id="tbl" name="tbl" value="<?php echo Arr::getValue($params, 'tbl', ''); ?>">
                <!--<p class="help-block">Вспомогательный текст</p>-->
            </div>
            <span class="help-inline"></span>
        </div>

        <div class="control-group">
            <label class="control-label" for="name">Название объекта</label>
            <div class="controls">
                <input type="text" class="input-xlarge" id="name" name="name" value="<?php echo Arr::getValue($params, 'name', ''); ?>">
            </div>
            <span class="help-inline"></span>
        </div>

        <div class="control-group">
            <label class="control-label" for="sen">Датчики</label>
            <div class="controls">
                <input type="text" class="input-xlarge" id="sen" name="sen" value="<?php echo Arr::getValue($params, 'sen', ''); ?>">
            </div>
            <span class="help-inline"></span>
        </div>

        <div class="control-group">
            <label class="control-label" for="description">Описание объекта</label>
            <div class="controls">
                <textarea class="input-xlarge" id="description" name="description" rows="3"><?php echo Arr::getValue($params, 'description', ''); ?></textarea>
            </div>
            <span class="help-inline"></span>
        </div>


        <div class="control-group">
            <label class="control-label" for="address">Адрес</label>
            <div class="controls">
                <textarea class="input-xlarge" id="address" name="address" rows="3"><?php echo Arr::getValue($params, 'address', ''); ?></textarea>
            </div>
            <span class="help-inline"></span>
        </div>


        <div class="control-group">
            <label class="control-label" for="photo">Фотографии объекта</label>
            <div class="controls">
                <input type="text" class="input-xlarge" id="photo" name="photo" value="<?php echo Arr::getValue($params, 'photo', ''); ?>">
            </div>
            <span class="help-inline"></span>
        </div>

        <div class="control-group">
            <label class="control-label" for="placed">Размещение компьютера</label>
            <div class="controls">
                <input type="text" class="input-xlarge" id="placed" name="placed" value="<?php echo Arr::getValue($params, 'placed', ''); ?>">
            </div>
            <span class="help-inline"></span>
        </div>



        <!--

        -->

        <div class="control-group">
            <label class="control-label" for="obj_type">Тип объекта</label>
            <div class="controls">
                <select id="obj_type" name="obj_type" class="input-xlarge">

                    <?php
                    $selvalue = Arr::getValue($params, 'obj_type', 0);
                    $obj_types = Arr::getValue($params, 'obj_types', array());
                    foreach ($obj_types as $key=>$val) {
                        $sel = ($key == $selvalue)? 'selected="selected"' : '';
                        $t = $key? ' ('.Arr::getValue($val, 'datatypename', '---').', '.Arr::getValue($val, 'unit', '').')' : '';
                        echo '<option value="'.$key.'" '.$sel.'>'.$val['name'].$t.'</option>';
                    }
                    ?>
                </select>
                <button type="button" class="btn btn-success" id="addOT-open"><i class="icon-plus icon-white"></i> Добавить </button>
                <span class="help-inline"></span>
            </div>
        </div>


        <div class="control-group">
        <label class="control-label" for="build_type">Тип помещения</label>
            <div class="controls">
                <select id="build_type" name="build_type" class="input-xlarge">

                    <?php
                    $selvalue = Arr::getValue($params, 'build_type', 0);
                    $btypes = Arr::getValue($params, 'btypes', array());
                    foreach ($btypes as $key=>$val) {
                        $sel = ($key == $selvalue)? 'selected="selected"' : '';
                        echo '<option value="'.$key.'" '.$sel.'>'.$val['name'].'</option>';
                    }
                    ?>
                </select>
                <span class="help-inline"></span>
            </div>
        </div>



        <div class="control-group">
        <label class="control-label" for="db_type">База данных</label>
            <div class="controls">
                <select id="db_type" name="db_type" class="input-xlarge">

                    <?php
                    $selvalue = Arr::getValue($params, 'db_type', 0);
                    $db_types = Arr::getValue($params, 'db_types', array());
                    foreach ($db_types as $row) {
                        $key = Arr::getValue($row, 'id', 0);
                        $val = Arr::getValue($row, 'name', '???');
                        $sel = ($key == $selvalue)? 'selected="selected"' : '';
                        echo '<option value="'.$key.'" '.$sel.'>'.$val.'</option>';
                    }
                    ?>
                </select>
                <button type="button" class="btn btn-success" id="addCDB-open"><i class="icon-plus icon-white"></i> Добавить </button>
                <span class="help-inline"></span>
            </div>
        </div>

        <div class="control-group">
            <label class="control-label" for="db_descr">БД - пояснение</label>
            <div class="controls">
                <input type="text" class="input-xlarge" id="db_descr" name="db_descr" value="<?php echo Arr::getValue($params, 'db_descr', ''); ?>">
            </div>
            <span class="help-inline"></span>
        </div>

        <div class="control-group">
            <label class="control-label" for="db_path">Путь к БД</label>
            <div class="controls">
                <input type="text" class="input-xlarge" id="db_path" name="db_path" value="<?php echo Arr::getValue($params, 'db_path', ''); ?>">
            </div>
            <span class="help-inline"></span>
        </div>

        <div class="control-group">
        <label class="control-label" for="app">Софт</label>
            <div class="controls">
                <select id="app" name="app" class="input-xlarge">
                    <?php
                    $selvalue = Arr::getValue($params, 'app', 0);
                    $apps = Arr::getValue($params, 'apps', array());
                    foreach ($apps as $row) {
                        $key = Arr::getValue($row, 'id', 0);
                        $val = Arr::getValue($row, 'name', '???');
                        $sel = ($key == $selvalue)? 'selected="selected"' : '';
                        echo '<option value="'.$key.'" '.$sel.'>'.$val.'</option>';
                    }
                    ?>
                </select>
                <button type="button" class="btn btn-success" id="addApp-open"><i class="icon-plus icon-white"></i> Добавить </button>
                <span class="help-inline"></span>
            </div>
        </div>


        <div class="control-group">
        <label class="control-label" for="os">Операционная система</label>
            <div class="controls">
                <select id="os" name="os" class="input-xlarge">

                    <?php
                    $selvalue = Arr::getValue($params, 'os', 0);
                    $oss = Arr::getValue($params, 'oss', array());
                    foreach ($oss as $row) {
                        $key = Arr::getValue($row, 'id', 0);
                        $val = Arr::getValue($row, 'name', '???');
                        $sel = ($key == $selvalue)? 'selected="selected"' : '';
                        echo '<option value="'.$key.'" '.$sel.'>'.$val.'</option>';
                    }
                    ?>
                </select>
                <span class="help-inline"></span>
            </div>
        </div>


        <div class="control-group">
            <label class="control-label" for="os_descr">Операционная система - пояснение</label>
            <div class="controls">
                <input type="text" class="input-xlarge" id="os_descr" name="os_descr" value="<?php echo Arr::getValue($params, 'os_descr', ''); ?>">
            </div>
            <span class="help-inline"></span>
        </div>

        <div class="control-group">
            <label class="control-label" for="remote">Параметры удаленного доступа</label>
            <div class="controls">
                <input type="text" class="input-xlarge" id="remote" name="remote" value="<?php echo Arr::getValue($params, 'remote', ''); ?>">
                <!--<p class="help-block">Вспомогательный текст</p>-->
            </div>
            <span class="help-inline"></span>
        </div>


        <div class="control-group">
            <label class="control-label" for="created">Дата подключения</label>
            <div class="controls">
                <input type="text" class="input-xlarge" id="created" name="created" value="<?php echo Arr::getValue($params, 'created', ''); ?>">
                <button type="button" class="btn btn-info" id="today-btn"><i class="icon-calendar icon-white"></i> Сегодня </button>
            </div>
            <span class="help-inline"></span>
        </div>






        <div class="form-actions">
            <button type="submit" class="btn btn-primary input-large"><i class="icon-ok icon-white"></i> Сохранить</button>
        </div>

    </fieldset>
</form>


<script type="text/JavaScript" src="js/jquery.ui.datepicker-ru.min.js"></script>

<?php
echo includeFile(APP_PAGE_PARTS.'forms/form_add_app.php');
echo includeFile(APP_PAGE_PARTS.'forms/form_add_objtype.php', $params);
echo includeFile(APP_PAGE_PARTS.'forms/form_add_cdbtype.php');
?>


<script>

function newDs_wrongfields(wf) {
    wf = wf || {};

    var wf_count = 0;

    $('#form_new_ds').find('div.alert').remove();
    for(var id in wf) {
        if (!wf.hasOwnProperty(id)) continue;
        var msg = wf[id];

        //$('#'+id).after($('<div class="help-inline alert alert-error">').html(msg));
        $('#'+id).parent().append($('<div class="help-inline alert alert-error">').html(msg));
        wf_count++;
    }
    return wf_count;
}





$(function() {

    $.datepicker.setDefaults($.datepicker.regional['ru']);
    $('#created').datepicker({
        dateFormat  : "yy-mm-dd",
        currentText : "Сегодня",
        closeText   : "Закрыть",
        showButtonPanel: false
    });

    if (!$('#created').val()) $('#created').datepicker( "setDate" , '0' );

    $('#today-btn').click(function(){ $('#created').datepicker( "setDate" , '0' ); });

    $('#form_new_ds').submit(function() {

        var wf = newDs_wrongfields({}); // Убираем все нотифаеры

        var send = $(this).serialize();
        jsonRequest(
            'install.php',
            send,

            function(data) {
                if(!checkSession(data)) {
                    Elm.loginFormModal.dialog('open');
                    return;
                }
                if (!data.state) {
                    uiAlert(data.message,'Error');
                    return;
                }
                if (data.hasOwnProperty('response_data') && data.response_data) {
                    var resp = data.response_data;
                    if (resp.hasOwnProperty('wrongFields')) {
                        wf = newDs_wrongfields(resp.wrongFields);
                    }
                }


                if (data.hasOwnProperty('relocate') && data.relocate) window.location.assign(data.relocate);
                else if (data.hasOwnProperty('request_data')
                        && data.request_data
                        && data.request_data.hasOwnProperty('action')
                        && (data.request_data.action = '<?php echo ACTIONS::INSTALL_EDITDS; ?>')
                        && !wf
                ){
                    uiAlert('Изменения сохранены','Информация');
                }
            },

            function() {
                uiAlert('Ошибка соединения','Error');
            }
        );
        return false;
    });





    Elm.addAppForm.submit(function(){
        var send = Elm.addAppForm.serialize();
        jsonRequest(
            'apps.php',
            send,

            function(data) {
                if(checkSession(data)) {
                    if (!data.state) {
                        uiAlert(data.message,'Error');
                        return;
                    }

                    if (data.hasOwnProperty('response_data') && data.response_data) {
                        var resp = data.response_data;
                        if (resp.hasOwnProperty('insertedId')) {
                            $('#app').append(
                                $('<option>').attr({value:resp.insertedId}).html($('#appname').val())
                            ).val(resp.insertedId);
                        }
                    }
                    Elm.addApp.dialog('close');
                }
                else Elm.loginFormModal.dialog('open');
            },

            function() {
                uiAlert('Ошибка соединения','Error');
            }
        );
            return false;
    });

    Elm.addApp.dialog({
        width       : 350,
        modal       : true,
        resizable   : false,
        title       : "Добавить софт",
        autoOpen    : false,
        buttons     : {}
    }).removeClass('hidden');









    Elm.addCDBForm.submit(function(){
        var send = Elm.addCDBForm.serialize();
        jsonRequest(
            'cdbtypes.php',
            send,

            function(data) {
                if(checkSession(data)) {
                    if (!data.state) {
                        uiAlert(data.message,'Error');
                        return;
                    }

                    if (data.hasOwnProperty('response_data') && data.response_data) {
                        var resp = data.response_data;
                        if (resp.hasOwnProperty('insertedId')) {

                            $('#db_type').append(
                                $('<option>').attr({value:resp.insertedId}).html($('#cdb_name').val())
                            ).val(resp.insertedId);
                        }
                    }
                    Elm.addCDB.dialog('close');
                }
                else Elm.loginFormModal.dialog('open');
            },

            function() {
                uiAlert('Ошибка соединения','Error');
            }
        );
            return false;
    });

    Elm.addCDB.dialog({
        width       : 350,
        modal       : true,
        resizable   : false,
        title       : "Добавить тип клиентской БД",
        autoOpen    : false,
        buttons     : {}
    }).removeClass('hidden');






    $('#addApp-open').click(function() {
        if (Elm.hasOwnProperty('addApp') && Elm.addApp) Elm.addApp.dialog('open');
    });

    $('#addOT-open').click(function() {
        addOTDialogOpen(function(data) {
            $('#obj_type').append(
                $('<option>').attr({value:data.id}).html($('#ot_name').val()+' ('+data.datatype+')')
            ).val(data.id);
        });
    });

    $('#addCDB-open').click(function() {
        if (Elm.hasOwnProperty('addCDB') && Elm.addCDB) Elm.addCDB.dialog('open');
    });


});

</script>